﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Caching.Memory;

namespace MyBlog.WebAPI;

public class CustomResourceFilterAttribute : Attribute, IResourceFilter
{
    private readonly IMemoryCache cache;
    public CustomResourceFilterAttribute(IMemoryCache cache)
    {
        this.cache = cache;
    }
    public void OnResourceExecuted(ResourceExecutedContext context)
    {
        string path = context.HttpContext.Request.Path;
        string route = context.HttpContext.Request.QueryString.Value;
        string key = path + route;//api/test/getcache?name=name

        cache.Set(key,context.Result);
    }

    public void OnResourceExecuting(ResourceExecutingContext context)
    {
        string path = context.HttpContext.Request.Path;
        string route = context.HttpContext.Request.QueryString.Value;
        string key = path + route;//api/test/getcache?name=name

        if(cache.TryGetValue(key, out var value))
        {
            context.Result = value as IActionResult;
        }

    }
}
